package com.bjb.vr.auth.security;

import com.bjb.vr.auth.service.LoginService;
import com.bjb.vr.auth.util.AccessRequestUtil;
import com.bjb.vr.common.constant.LoginConstant;
import com.bjb.vr.common.constant.LoginTypeEnum;
import com.bjb.vr.common.constant.ThreadLocalConstant;
import com.bjb.vr.common.constant.TokenConstants;
import com.bjb.vr.common.dto.SysLogin;
import com.bjb.vr.common.result.CommonResult;
import com.bjb.vr.common.service.SysLoginService;
import com.bjb.vr.common.vo.UmsAccountVo;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.Objects;

/**
 * 退出成功处理器
 *
 * @version 1.0.0
 * @author: HuJingBo
 * @time: 2022/4/8 10:21
 */
@Slf4j
@Component
public class RequestLogoutSuccessHandler implements LogoutSuccessHandler {

    @Resource
    private LoginService loginService;

    @Resource
    private SysLoginService sysLoginService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String tips = "退出成功";
        if (Objects.nonNull(authentication)) {
            log.info("{} " + tips, authentication.getName());
        } else {
            log.info(tips);
        }
        Map<String, String> headers = AccessRequestUtil.takeHeaders();
        String host = headers.get(ThreadLocalConstant.USER_HOST);
        UmsAccountVo umsAccountVo = loginService.getUserAccount(headers.get(TokenConstants.AUTHORIZATION.toLowerCase()));
        // 保存到系统登录表
        SysLogin sysLogin = new SysLogin();
        sysLogin.setLoginPlatform(LoginTypeEnum.valueOf(umsAccountVo.getLoginType().toUpperCase()).getLoginTypeValue());
        sysLogin.setTenantId(umsAccountVo.getTenantId());
        sysLogin.setAccountId(umsAccountVo.getId());
        sysLogin.setUserName(umsAccountVo.getUsername());
        sysLogin.setStatus(LoginConstant.LOGIN_SUCCESS);
        sysLogin.setIpaddr(host);
        sysLogin.setAccessTime(LocalDateTime.now());
        sysLogin.setMsg(LoginConstant.LOGOUT_SUCCESS_MSG);
        sysLoginService.saveLoginInfo(sysLogin);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(new ObjectMapper().writeValueAsString(CommonResult.Ok(tips)));
    }
}
